gpt4 book ai didi

c++ - new[size] object(args ... ) ,数组 new [-fpermissive] 中的 GCC 括号初始化器

转载 作者:太空狗 更新时间:2023-10-29 21:45:58 25 4
gpt4 key购买 nike

我的代码有一个我不太理解的问题。

我使用 «gcc 版本 4.7.2 (Ubuntu/Linaro 4.7.2-2ubuntu1)»


编辑:我用这一行来编译

g++ -g -std=c++0x -o "GeneticEngine.o" -c "GeneticEngine.cpp" 

这是我遇到的错误:

GeneticEngine.tpl:16:5: erreur: parenthesized initializer in array new [-fpermissive]

这是我的(最小化)代码:


基因引擎.hpp

#include "GeneticThread.hpp"

template <class T>
class GeneticEngine
{
public:
template <typename ... Args>
GeneticEngine(int nb_threads,float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args);

/* Other code */


private:
GeneticThread<T>* islands; /* Cause of error */

int size;
};

#include "GeneticEngine.tpl"

基因引擎.tpl

template <class T>
template <typename ... Args>
GeneticEngine<T>::GeneticEngine(int nb_threads,float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args) : size(nb_threads)
{
/*next line is 16 : Error */
islands = new GeneticThread<T>[size](taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...);
};

基因线程.hpp

template <class T>
class GeneticThread
{
public:
template <typename ... Args>
GeneticThread(float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args)
{ /* code ... */ };
/* Other code */
};

我读过这个 ( Initializing arrays when using templates ) 但它并不完全相同。

如果你有想法在没有的情况下修复它:[最后我用这个:/]

GeneticThread<T>** islands;
islands = new GeneticThread<T>*[size];
for(int i=0;i<size;++i)
islands[i] = new GeneticThread<T>(taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...);

我想要:

 GeneticThread<T>* islands;

有办法吗???

我尝试:

islands = new  (GeneticThread<T>[size](taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...));

 islands = new  GeneticThread<T>(taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...)[size];

但它不起作用。


谢谢。

最佳答案

您不能为分配的数组使用非默认构造函数。

与其像这样使用 new,不如使用 vector 并将正确构造的对象传递给 vector 构造函数!即使您永远不需要调整大小,vector 也会确保您的内存得到妥善管理,不会泄漏。

例如:

std::vector<GeneticThread<T>*> islands;

然后:

GeneticEngine<T>::GeneticEngine(int nb_threads,float taux_mut,int tranche_mut,std::string filename,int pop_size,Args& ... args)
: size(nb_threads), islands(size, GeneticThread<T>(taux_mut,tranche_mut,filename,pop_size/nb_threads,std::forward<Args>(args)...))
{
};

关于c++ - new[size] object(args ... ) ,数组 new [-fpermissive] 中的 GCC 括号初始化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16404829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com