0

下面的代码在未注释时崩溃,并且 get() 中的 shared_array<> 参数似乎有问题。

print() 至少现在似乎没有崩溃......

传递 shared_array<> 参数的正确方法是什么?

#include <iostream>
#include <cstring>
#include <boost/shared_array.hpp>
using namespace std;
using namespace boost;

shared_array<wchar_t> get(const wchar_t* s) {
//shared_array<wchar_t> get(const shared_array<wchar_t>& s) {

    size_t size = wcslen(s);
    //size_t size = wcslen(s.get());

    shared_array<wchar_t> text(new wchar_t[size+1]);

    wcsncpy(text.get(), s, size+1);
    //wcsncpy(text.get(), s.get(), size+1);

    return text;
}

void print(shared_array<wchar_t> text) {
    wcout << text.get() << endl;
}

int wmain(int argc, wchar_t *argv[]) {
    //shared_array<wchar_t> param(argv[1]);

    shared_array<wchar_t> text = get(argv[1]);
    //shared_array<wchar_t> text = get(param);

    print(text);
    //print(text.get()); 
}

编辑:谢谢。所以这里的关键是在使用 boost::shared_ptr/array 时我应该始终只使用 new/new[]。

主要功能固定:

int wmain(int argc, wchar_t *argv[]) {
    size_t szArg = wcslen(argv[1]);
    wchar_t* paramBuf = new wchar_t[szArg+1];
    wcscpy_s(paramBuf, szArg+1, argv[1]);
    shared_array<wchar_t> param(paramBuf);

    shared_array<wchar_t> text = get(param);

    print(text);
}

实际上,起初我在堆栈中分配了 paramBuf,所以我找不到错误。

WRONG:    
int wmain(...) {
    wchar_t paramBuf[100];
    wcscpy_s(paramBuf, 100, argv[1]);
    ...
}
4

1 回答 1

5

问题在于:

shared_array<wchar_t> param(argv[1]);

shared_array 需要使用指向使用 new[] 分配的数组的指针进行初始化,但 argv[1] 只是一个 c 字符串,因此当它超出范围(即变量参数)时,shared_array 的析构函数会调用 delete[] argv[1] 这是不允许的。

于 2012-09-30T13:35:09.620 回答