通过向构造函数其他对象引用页面来创建对象

Create an object by paasing to the constructor other object reference

本文关键字:创建对象 对象引用 其他 构造函数      更新时间:2023-10-16

我在include.hpp中创建了两个C++类:

#include <string>
#include <map>
#include <iostream>
#include <sstream>
#include<vector>
using namespace std;
class A {
public:
vector<char> v;
A(){};
A(A &other) {
v = other.v;
}
A(string s) {
v.assign(s.begin(), s.end());
}
A& operator << (std::string s) {
v.insert(v.end(), s.begin(), s.end());
return(*this);
};
};
class B {
protected:
A a;
public:
template<typename T>
B(T &t): a(t) {}
};

我现在需要通过在其构造函数中输入一个 A 对象来创建实例。 此外,A 对象必须是另一个函数的返回值,该函数使用运算符 <<创建返回的 A 实例

我正在尝试使用以下主要方法:

#include<iostream>
#include "include.hpp"
using namespace std;
A& createstrbyappend() {
A a;
a << "aa";
return a;
}
int main() {
A aa;
aa << "kkk";
cout << "create b1 object " << endl;
B* b1 = new B(aa);
cout << "create b2 object " << endl;
B* b2 = new B(createstrbyappend());
cout << "End program " << endl;
}

但是我在这个主要方面遇到了分段错误,我得到输出:

create b1 object 
create b2 object 
Segmentation fault (core dumped)

B1 创建成功,但通过函数 createstrbyappend 创建的 B2 会出现分段错误。

有没有建议我如何解决这个问题?

编辑:添加编译器版本

我正在 ubuntu 下使用 g++ 命令进行编译。 我的 G++ 版本如下:

$ g++ --version
g++ (Ubuntu 5.4.0-6ubuntu1~16.04.12) 5.4.0 20160609
Copyright (C) 2015 Free Software Foundation, Inc.
This is free software; see the source for copying conditions.  There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

您正在通过引用从createstrbyappend返回函数本地对象。您应该返回一份副本:

A createstrbyappend() {
//...
}

这要求你把参数也按值B构造函数:

template<typename T>
B(T t): a(std::move(t)) {}

现在,您需要将参数带到A的复制构造函数中const&

A(A const &other) {
v = other.v;
}

这是一个工作演示。