相关疑难解决方法(0)

C++,是否可以直接调用构造函数,而不需要新的?

new如果我已经有对象的内存,我可以显式调用构造函数而不使用吗?

class Object1{
    char *str;
public:
    Object1(char*str1){
        str=strdup(str1);
        puts("ctor");
        puts(str);
    }
    ~Object1(){
        puts("dtor");
        puts(str);
        free(str);
    }
};

Object1 ooo[2] = {
     Object1("I'm the first object"), Object1("I'm the 2nd")
};

do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor
ooo[0].Object1("I'm the 3rd object in place of first"); // ???? - reuse memory
Run Code Online (Sandbox Code Playgroud)

c++ constructor placement-new

51
推荐指数
4
解决办法
3万
查看次数

匿名结构作为返回类型

以下代码可以在vc ++ 19.00.23506(标志:)/Wall /WX /Zavc ++ 19.10.25109.0(标志:/Wall /WX /Za /permissive-,可以在http://webcompiler.cloudapp.net上进行检查)下正常编译,但不能与clang 3.8.0一起编译。g ++ 6.3.0(标志:)-std=c++11 -Wall -Wextra -Werror -pedantic-errors。这是vc ++中的错误吗?标准是否禁止这种构造?

struct
{
}
foo()
{
    return {};
}

int main()
{
}
Run Code Online (Sandbox Code Playgroud)

c++ struct return-type visual-c++ function-declaration

2
推荐指数
1
解决办法
686
查看次数